package com.young.common.client.ums;

import com.young.common.util.CommonConstants;
import com.young.common.util.JsonUtil;
import com.young.common.util.StringUtils;
import com.young.interfaces.ums.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * cloud环境下的登录用户服务
 * @author imrookie
 * @date 2018/9/30
 */
@Service("cloudLoginUser")
@ConditionalOnProperty(
        name = "young.interceptor.ums-client-interceptor.loginUserService",
        havingValue = "cloudLoginUser",
        matchIfMissing = false
)
public class CloudLoginUser implements ILoginUser {

    private static final Logger logger = LoggerFactory.getLogger(CloudLoginUser.class);

    /**
     * 获取当前登录用户信息
     * 1.从请求体和cookie还有header中获取令牌
     * 2.调用服务验证token
     *
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        String userFromRequest = request.getHeader(CommonConstants.HEADER_GATEWAY_USER_INFO);
        logger.debug("[Cloud登录用户服务] 获取网关用户信息header.gateway_user_info={}", userFromRequest);
        if (StringUtils.isNotBlank(userFromRequest)) {
            User user = null;
            try {
                user = JsonUtil.toBean(URLDecoder.decode(userFromRequest, "UTF-8"), User.class);
            } catch (UnsupportedEncodingException e) {
                logger.error("[Cloud登录用户服务] 用户信息解码发生异常,gateway_user_info={}", userFromRequest, e);
            }
            logger.debug("[Cloud登录用户服务] 当前登录用户信息打印:{}", user);
            return user;
        } else {
            logger.info("[Cloud登录用户服务] 网关用户信息header.gateway_user_info为空(若是rpc调用,可忽略,rpc通常直接参数传递用户信息),url={}", request.getRequestURL());
        }
        return null;
    }

    /**
     * 校验用户是否有权限访问
     *
     * @param user 用户
     * @param uri  uri
     * @return
     */
    @Override
    public boolean canAccessUri(User user, String uri) {
        return true;
    }
}
